<template>
  <a-form
    ref="formRef"
    :model="formData"
    class="form"
    :label-col-props="{ span: 8 }"
    :wrapper-col-props="{ span: 16 }"
  >
    <a-form-item
      field="username"
      label="用户名"
      :rules="[
        {
          required: true,
          message: '请输入用户名'
        }
      ]"
    >
      <a-input v-model="formData.username" placeholder="请输入您的用户名" />
    </a-form-item>
    <a-form-item
      field="profile"
      label="个人简介"
      :rules="[
        {
          maxLength: 200,
          message: '个人简介不能超过200字'
        }
      ]"
      row-class="keep-margin"
    >
      <a-textarea
        v-model="formData.profile"
        placeholder="请您输入您的个人简介，最多不超过200字"
      />
    </a-form-item>
    <a-form-item>
      <a-space>
        <a-button type="primary" @click="validate">保存</a-button>
        <a-button type="secondary" @click="reset">重置</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { updateMyUserUsingPost } from '@/service/backend/userController.ts';
import { Message } from '@arco-design/web-vue';
import useUser from '@/hooks/useUser.ts';
import { useUserStore } from '@/store';

const userStore = useUserStore();
const { loginUser } = userStore;
const { logout } = useUser();
const formRef = ref<FormInstance>();
const formData = ref({
  username: '',
  profile: ''
});

onMounted(() => {
  formData.value = {
    ...loginUser
  };
});

const validate = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    try {
      await updateMyUserUsingPost({ ...formData.value });
      await logout();
    } catch (e) {
      Message.error(e.message);
    }
  }
};
const reset = async () => {
  await formRef.value?.resetFields();
};
</script>

<style scoped lang="less">
.form {
  width: 540px;
  margin: 0 auto;
}
</style>
